package logic

import (
	"context"
	"fmt"
	"strconv"
	"thing/model/cache"

	"thing/thingrpc/internal/svc"
	"thing/thingrpc/thingrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *thingrpc.CartListRequest) (*thingrpc.CartListResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("cart:%d:*", in.UserId)

	keys := cache.Rdb.Keys(l.ctx, key).Val()

	var nut []*thingrpc.CartList

	for _, k := range keys {
		cacheAll := cache.Rdb.HGetAll(l.ctx, k).Val()
		id, _ := strconv.Atoi(cacheAll["id"])
		price, _ := strconv.ParseFloat(cacheAll["price"], 64)
		quantity, _ := strconv.ParseInt(cacheAll["quantity"], 10, 64)

		item := thingrpc.CartList{
			GoodsId:  int64(id),
			Name:     cacheAll["name"],
			Price:    float32(price),
			Image:    cacheAll["image"],
			Quantity: quantity,
		}
		nut = append(nut, &item)
	}

	return &thingrpc.CartListResponse{
		List: nut,
	}, nil
}
